import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;

import com.delphi.tcde.plug.editor.GraphEditor;
import com.delphi.tcde.plug.model.io.GraphWriter;


public class SaveToFile implements IWorkbenchWindowActionDelegate {

	@Override
	public void run(IAction action) {
		saveFile();
		// TODO Auto-generated method stub

	}

	@Override
	public void selectionChanged(IAction action, ISelection selection) {
		// TODO Auto-generated method stub

	}

	@Override
	public void dispose() {
		// TODO Auto-generated method stub

	}

	@Override
	public void init(IWorkbenchWindow window) {
		// TODO Auto-generated method stub

	}
	
    private void saveFile() {
        Shell shell = Display.getDefault().getActiveShell();
        FileDialog dialog = new FileDialog(shell, SWT.SAVE);
        dialog.setText("Save Genealogy Graph");
        String path = dialog.open();
        if (path == null) return;
        PrintWriter writer;
        File file = new File(path);
        if (file.exists()) {
        if (!MessageDialog.openQuestion(shell, "Overwrite?", "Overwrite the existing file?\n" + path))
        return;
        }
        try {
        writer = new PrintWriter(file);
        }
        catch (FileNotFoundException e) {
        e.printStackTrace();
        return;
        }
        try {
        new GraphWriter(GraphEditor.gg()).write(writer);
        }
        finally {
        writer.close();
        }
        }

}
